package com.whilelife.Wachovia.account;

import java.io.BufferedReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * Handles data within the "Deposits and Other Credits" section
 * Date: Nov 3, 2011
 * Time: 3:00:25 PM
 * @author Brent Merle
 */
public class Deposit extends Transaction {

  public Deposit(double val, String date, String descr) {
    super(val, date, descr);
  }

  public static List<Deposit> parseDeposits(BufferedReader br, int endYear) throws IOException {
    ArrayList<Deposit> deposits = new ArrayList<Deposit>();
    String line;
    br.readLine(); //move past the header line
    Deposit d = null;
    int firstMonth = -1;
    int year = endYear;
    while ((line = br.readLine()) != null && !line.toLowerCase().startsWith("total")) {
      line = line.trim();
      if (line.matches(TRANSACTION_REGEX)) {
        if (d != null) {
          deposits.add(d);
        }
        int idx = line.indexOf(' ', 0);
        String date = line.substring(0, idx);
        int month = Integer.parseInt(date.substring(0, date.indexOf('/')));
        if (month < 10) {
          date = '0' + date;
        }
        if (firstMonth == -1) {
          firstMonth = month;
          if (month == 12) {
            year--;
          }
        } else if (month < firstMonth) {
          firstMonth = month;
          year++;
        }
        date += '/' + String.valueOf(year);
        double val = Double.parseDouble(line.substring(idx, idx = line.indexOf(' ', idx + 1)).replaceAll(",", ""));
        String desc = line.substring(idx);
        d = new Deposit(val, date, desc);
      } else if (line.equalsIgnoreCase("Deposits and Other Credits continued on next page.")) {
          while (!(br.readLine().trim().equalsIgnoreCase("Date Amount Description"))) {
           //Skips the header (on continuation pages)
          }
      } else if (d != null) {
        d.setDescription(d.getDescription() + ' ' + line);
      }
    }

    if (d != null && !deposits.contains(d)) {
      deposits.add(d);
    }
    return deposits;
  }

  public static double sumDeposits(List<Deposit> deposits) {
    double sum = 0.0;
    for (Deposit deps : deposits) {
      sum += deps.getValue();
    }
    System.out.println("average is: " + sum / deposits.size());
    return sum;
  }


}
